package com.main.hotel.controller;

import com.main.hotel.entity.*;
import com.main.hotel.service.*;
import com.main.hotel.util.RandomValidateCodeUtil;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.logging.Logger;

@Controller

@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private ManagerTokenService managerTokenService;
    @Autowired
    private RoomTypeService roomTypeService;
    @Autowired
    private ManageService manageService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private BillService billService;
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/confirm")//访问路径：
    @ResponseBody
    public ManagerResult confirmManager(Manager manager, @RequestParam("verifyInput") String verifyInput, HttpSession session) {
        //System.out.println(id);
        ManagerResult result = new ManagerResult();

        String inputStr = verifyInput;
        String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        System.out.println(manager.getPassword() + "   " + manager.getPhone() + "   88");
        Manager manager2 = managerService.confirmManager(manager.getPhone(), manager.getPassword());
        System.out.println(manager2.toString() + "  99");
        if (random == null) {
            return null;
        }
        if (random.equals(inputStr)) {

            if (manager2 == null)
                return null;

            result.setManager_id(manager2.getManager_id());
            ManagerToken managerToken = managerTokenService.findByManagerId(manager2.getManager_id());
            //为生成Token准备
            String TokenStr = "";
            Date date = new Date();
            int nowtime = (int) (date.getTime() / 1000);
            //生成Token
            TokenStr = creatToken(manager2, date);
            if (null == managerToken) {
                //第一次登陆
                managerToken = new ManagerToken();
                managerToken.setToken(TokenStr);
                managerToken.setBuild_time(nowtime);
                managerToken.setManager_id(manager2.getManager_id());
                managerTokenService.addToken(managerToken);
            } else {
                //登陆就更新Token信息
                TokenStr = creatToken(manager2, date);
                managerToken.setToken(TokenStr);
                managerToken.setBuild_time(nowtime);
                managerTokenService.updataToken(managerToken);
            }
            result.setTokenString(TokenStr);

            return result;

        }
        ManagerResult managerResult = new ManagerResult();
        managerResult.setManager_id(100);
        managerResult.setTokenString("2");
       return managerResult;
    }

    //生成Token信息方法（根据有效的用户信息）
    private String creatToken(Manager manager, Date date) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") // 设置header
                .setHeaderParam("alg", "HS256").setIssuedAt(date) // 设置签发时间
                .setExpiration(new Date(date.getTime() + 1000 * 60 * 60 * 24 * 3))
                .claim("manager_id", String.valueOf(manager.getManager_id())) // 设置内容
                .setIssuer("lws")// 设置签发人
                .signWith(signatureAlgorithm, "dahao"); // 签名，需要算法和key
        String jwt = builder.compact();
        return jwt;


    }

    @RequestMapping("roomtype/add")
    @ResponseBody
    public String addroomtype(RoomType roomType){

        int result=roomTypeService.addroomtype(roomType);
        if(result==1)
            return "true";
        else
            return "false";
    }
    @RequestMapping("roomtype/delete")
    @ResponseBody
    public String deleteroomtype(RoomType roomType){

        int result=roomTypeService.deleteRoomTypeById(roomType.getRoomtype_id());
        if(result==1)
            return "删除成功";
        else
            return "删除失败";
    }
    @RequestMapping("roomtype/update")
    @ResponseBody
    public String updateroomtype(RoomType roomType){

        int result=roomTypeService.updataRoomType(roomType);
        if(result==1)
            return "更新成功";
        else
            return "更新失败";

    }

    @RequestMapping("manage/add")
    @ResponseBody
    public String addCustomer(Customer customer){

        int result=manageService.addCustomer(customer);
        if(result==1)
            return "true";
        else
            return "false";
    }

    @RequestMapping("manage/delete")
    @ResponseBody
    public String deleteCustomer(Customer customer){

        int result=manageService.deleteCustomerByCustomer_id(customer.getCustomer_id());
        if(result==1)
            return "删除成功";
        else
            return "删除失败";
    }
    @RequestMapping("manage/update")
    @ResponseBody
    public String updateCustomer(Customer customer){


        Date date=new Date();
        System.out.println(date.toString());
        customer.setCreate_date(date);
        int result=manageService.updateCustomer(customer);
        if(result==1)
            return "更新成功";
        else
            return "更新失败";

    }

    //入住登记
    @RequestMapping("checkin/in")
    @ResponseBody
    public String checkInRoom(Room room) {
        int result = roomService.updateRemarkAndOrder_idByRoom_number(room.getRoom_number(), room.getRemark(), room.getOrder_id());

        room = roomService.findByRoom_number(room.getRoom_number());

        OrderInfo orderInfo = orderInfoService.getOrderById(room.getOrder_id());
        Bill bill = new Bill();
        bill.setCustomer_id(orderInfo.getFoo());
        bill.setRoom_id(room.getRoom_id());
        bill.setCost(orderInfo.getOrder_cost());
        billService.addBill(bill);

        if (result == 1)
            return "入住成功";
        else
            return "入住失败";
    }

    //新增房间
    @RequestMapping("checkin/add")
    @ResponseBody
    public String AddRoom(Room room) {
        room.setRoom_type("111");
        int result = roomService.addRoom(room);
        if (result == 1)
            return "新增房间成功";
        else
            return "新增房间失败";
    }

    //退房
    @RequestMapping("checkin/out")
    @ResponseBody
    public String checkOutRoom(Room room) {
        int result = roomService.updateRoomStatusByRoom_id(room.getRoom_id(), 4);
/*        roomService.updateRemarkAndOrder_idByRoom_number(room.getRoom_number(), "无", "无");*/
        if (result == 1)
            return "1";
        else
            return "0";
    }
    //修改单个客房信息
    @RequestMapping("checkin/modify")
    @ResponseBody
    public String modifyRoom(Room room) {
        room.setRoom_type("111");
        int result = roomService.addRoom(room);
        if(result==1)
            return "修改成功";
        else
            return "修改失败";
    }

    @RequestMapping(value = "checkin/addbill")
    @ResponseBody
    public String addBill(Bill bill){

        int result = billService.addBill(bill);
        if(result==1)
            return "添加成功";
        else
            return "添加失败";
    }

}



